package com.benyi.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; 
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Date;

public class Serialize {

	public Serialize() {
		super();
	}
	
	public static <T extends Serializable> T clone(T object) throws Exception{
		if(object==null){
			return null;
		}
		if( !(object instanceof Serializable) ){
			throw new Exception("Can't create Object from Not-Serializable Object !");
		}
		byte []data=toBytes(object);
		T n=(T) toObject(data);
		return n;
	}
	
	public static void writeObject(Serializable obj, OutputStream outputStream) throws Exception {
		if (outputStream == null) {
			throw new IllegalArgumentException("The OutputStream must not be null");
		}
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(outputStream);
			out.writeObject(obj);
		} catch (IOException ex) {
			throw new IOException(ex);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException ex) {
				// ignore
			}
		}
	}

	public static byte[] toBytes(Serializable obj) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
		writeObject(obj, baos);
		return baos.toByteArray();
	}

	public static Serializable readObject(InputStream inputStream) throws Exception {
		if (inputStream == null) {
			throw new IllegalArgumentException("The InputStream must not be null");
		}
		ObjectInputStream in = null;
		try { 
			in = new ObjectInputStream(inputStream);
			return (Serializable)in.readObject();

		} catch (ClassNotFoundException ex) {
			throw ex;
		} catch (IOException ex) {
			throw new IOException(ex);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
	}

	public static Serializable toObject(byte[] objectData) throws Exception {
		if (objectData == null) {
			throw new IllegalArgumentException("The byte[] must not be null");
		}
		ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
		return readObject(bais);
	}


	public static void main(String[] args) throws Exception {
		Date d = new Date();
		System.out.println(d);
		Date d2 = Serialize.clone(d);
		System.out.println(d2); 
	}

}